
import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


def logout():
    print("开始退出-------------")
    try:
        time.sleep(15)
        driver.switch_to.window(original_window)
        WebDriverWait(driver, 20).until(
            EC.visibility_of_element_located((By.XPATH, "//span[text()='个人资料']"))
        )


        driver.find_element(By.XPATH, "//span[text()='个人资料']").click()

        time.sleep(1)

        driver.find_element(By.XPATH, "//span[text()='设置']").click()

        time.sleep(1)

        driver.find_element(By.XPATH, "//p[text()='退出']").click()
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
        print("没有找到退出按钮，跳过。。。")

def nextBtn():
    try:
        # 查找要操作的元素
        WebDriverWait(driver, 30).until(
            EC.presence_of_element_located((By.XPATH, "//button"))
        )
        # 下一步按钮
        tbns = driver.find_elements(By.TAG_NAME, "button")

        for e in tbns:
            try:

                print(e.text)
                # 使用JavaScript获取元素的innerHTML
                inner_html = ''
                if e is not None:
                    inner_html = driver.execute_script('return arguments[0].innerHTML', e)

                print(inner_html)

                if e.text == '下一步' or e.text == '连接' or e.text == '批准' or e.text == '切换网络' or e.text == '明白了' or e.text == '签名' :
                    print("点击了： ")
                    print(e.text)
                    e.click()
                    time.sleep(2)
                else:
                    if inner_html.index('明白了') > 0 :
                        e.click()
                        time.sleep(2)
                    print("没有找到匹配的点击按钮 ")
            except Exception as err:
                print(f"Unexpected {err=}, {type(err)=}")
                print("获取元素出现异常，遍历下一个！ ")

    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
        print("没有下一步按钮，跳过。。。")



def passwordLogin():
    try:
        WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.ID, "password"))
        )

        pwdElement = driver.find_element(By.ID, "password")

        #账号的密码
        pwdElement.send_keys("-----------登录账户密码--------------------")
        # 查找要登录的钱包点击
        driver.find_element(By.CSS_SELECTOR, "button[data-testid='unlock-submit']").click()

        nextBtn()
        nextBtn()
        nextBtn()
        nextBtn()
        nextBtn()

        time.sleep(2)
        if endCheck() :
            nextBtn()
            nextBtn()
            nextBtn()

        if endCheck() :
            nextBtn()
            nextBtn()
            nextBtn()
        return False
    except Exception as err:

        print(f"Unexpected {err=}, {type(err)=}")
        print("没有密码输入框，不用密码登录")
        
        return True


def endCheck():
    try:
        # 等待新窗口出现
        WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)

        # 切换窗口
        for window_handle in driver.window_handles:
            if window_handle != original_window:
                driver.switch_to.window(window_handle)
                break
        print("------有新窗口----，切换到新窗口-----")
        return True
    except:
        print("没有新窗口----")
        return False

#开始入口：  创建driver对象， 带插件的浏览器同一时间只能打开一个
option = webdriver.ChromeOptions()
option.add_argument("--user-data-dir="+r"C:/Users/Administrator/AppData/Local/Google/Chrome/User Data/")

driver=webdriver.Chrome(options=option)
driver.maximize_window()  #窗口最大化
driver.get('https://app.myshell.ai/zh/')  #打开网站


WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.XPATH,"//span[text()='个人资料']"))
    )

#登录按钮
driver.find_element(By.XPATH,"//span[text()='个人资料']").click()

time.sleep(1)

original_window = driver.current_window_handle
#查找要登录的钱包点击
driver.find_elements(By.CSS_SELECTOR,"img[alt='wallet connect']")[1].click()


time.sleep(20)

#等待新窗口出现
WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)

#切换窗口
for window_handle in driver.window_handles:
    if window_handle != original_window:
        driver.switch_to.window(window_handle)
        break



print("---等待20秒，或者直到有密码输入框--")
#等待20秒，或者直到有密码输入框
passwordLogin()

logout()

time.sleep(150)
